#include "stdafx.h"
#include "string_func.h"

#include "utf8.h"

static int s_nCompareCache[256][256];

int _appro_compare(const char* pcszPattern, int nPatternLen, const char* pcszString, int nStringLen)
{
	int nResult = 0;

	PROCESS_ERROR(nPatternLen > 0 && nStringLen > 0);

	if (s_nCompareCache[nPatternLen][nStringLen] != 0xFFFFFFFF)
		return s_nCompareCache[nPatternLen][nStringLen];

	int nMatch = 0;
	if (*pcszPattern == *pcszString)
		nMatch = 10;

	int nCase0 = _appro_compare(pcszPattern + 1, nPatternLen - 1, pcszString + 1, nStringLen - 1) + nMatch;
	int nCase1 = _appro_compare(pcszPattern, nPatternLen, pcszString + 1, nStringLen - 1) - 1;
	int nCase2 = _appro_compare(pcszPattern + 1, nPatternLen - 1, pcszString, nStringLen) - 1;

	nResult = nCase0 > nCase1 ? nCase0 : nCase1;
	nResult = nResult > nCase2 ? nResult : nCase2;
Exit0:
	s_nCompareCache[nPatternLen][nStringLen] = nResult;

	return nResult;
}

int appro_compare(const char* pcszPattern, const char* pcszString)
{
	LOG_PROCESS_ERROR(pcszPattern);
	LOG_PROCESS_ERROR(pcszString);

	int nPatternLen = strnlen(pcszPattern, 256);
	int nStringLen = strnlen(pcszString, 256);

	LOG_PROCESS_ERROR(nPatternLen < 256);
	LOG_PROCESS_ERROR(nStringLen < 256);

	memset(s_nCompareCache, 0xFF, sizeof(s_nCompareCache));

	return _appro_compare(pcszPattern, nPatternLen, pcszString, nStringLen);
Exit0:

	return 0;
}

int utf8_2_utf16(const char* pcszSrc, size_t uSrcLen, wchar_t* pszDest, size_t uDestLen)
{
	return utf8_to_wchar(pcszSrc, uSrcLen, pszDest, uDestLen, UTF8_IGNORE_ERROR | UTF8_SKIP_BOM);
}

int utf16_2_utf8(const wchar_t* pcszSrc, size_t uSrcLen, char* pszDest, size_t uDestLen)
{
	return wchar_to_utf8(pcszSrc, uSrcLen, pszDest, uDestLen, UTF8_IGNORE_ERROR | UTF8_SKIP_BOM);
}
